<template>
  <div class="page-list-live">
    <PageList>
      <template #header>员工管理</template>
      <template #filter>
        <ListFilter ref="ListFilter" :form="topFilter" :key-list="keyList" @search="handleSearch" @reset="handleReset" @changItemHandler="changItemHandler"></ListFilter>
      </template>
      <template #tips>
        <el-button icon="el-icon-delete" type="danger" @click="batchDeletion">批量删除</el-button>
        <el-button icon="el-icon-document-add" type="primary" @click="handleAdd">新增</el-button>
        <el-button icon="el-icon-document-add" type="primary" @click="addHandle">自定义表头</el-button>
        <el-upload
          ref="imgRef"
          style="display: inline-block;margin: 0 10px;"
          class="upload-demo"
          action
          :http-request="uploadFile"
          :headers="{
            Authorization: `Bearer ${$store.getters.token}`
          }"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
        >
          <el-button icon="el-icon-folder-add" type="primary">批量导入</el-button>
        </el-upload>
        <el-button icon="el-icon-folder-remove" type="primary" @click="handleOut">批量导出</el-button>
        <!-- <el-button :loading="downloadLoading" icon="el-icon-folder-remove" type="primary" @click="handleDownload">下载模板</el-button> -->
        <a :href="$imgUrl + '/files/employees.xlsx'" target="_self" class="download">
          <i class="el-icon-folder-remove"></i>下载模板
        </a>
        <el-button icon="el-icon-picture-outline" type="primary" @click="addHeadPortrait">导入头像</el-button>
      </template>
      <template #table>
        <ListTable ref="RefListTable" :loading="tableLoading" :table-data="tableData" :table-col="tabList" @selectChange="handleSelectionChange">
          <template slot="col2" slot-scope="stData">
            <div>
              <p v-if="!stData.row.photo">未上传</p>
              <el-image v-else style="height: 100px; width: 80px;" :src="stData.row.photo" :preview-src-list="[stData.row.photo]"></el-image>
            </div>
          </template>
          <template slot="col1" slot-scope="scope">
            <el-button
              icon="el-icon-s-release"
              :loading="scope.row.loadingEdit"
              size="mini"
              type="text"
              @click="setEmployeeHandle(scope.row)"
            >{{ scope.row.isEnable ? '禁用' : '启用' }}门禁</el-button>
            <el-button icon="el-icon-s-release" :loading="scope.row.loadingEdit" size="mini" type="text" @click="handleRowSee(scope.row)">详情</el-button>
            <el-button icon="el-icon-edit" :loading="scope.row.loadingEdit" size="mini" type="text" @click="handleRowEdit(scope.row)">编辑</el-button>
            <el-button :loading="scope.row.loadingDel" size="mini" icon="el-icon-delete" style="color: red;" type="text" @click="handleRowDel(scope.row)">删除</el-button>
          </template>
        </ListTable>
      </template>
    </PageList>
    <!-- 新增员工组件 -->
    <AddStaff ref="RefAccountsEdit" @success="afterEditSuccess"></AddStaff>
    <!-- 导入头像组件 -->
    <HeadPortrait ref="HeadPortrait"></HeadPortrait>
    <!-- 选择列表字段组件 -->
    <ListFields ref="ListFields" @setTableCol="setTableColHandler"></ListFields>
  </div>
</template>
<script>
  import listMixin from "@/mixins/list"
  import AddStaff from "./components/AddStaff"
  import HeadPortrait from "./components/HeadPortrait"
  import ListFields from "./components/ListFields"
  import ListFilter from "@/components/ListFilter"
  import { assetsImages } from '@/utils/images.js'
  import { employee, setEmployee, department, job, work, importEmployee, files, employees } from "@/api/api"
  import xlsx from 'node-xlsx'
  import fs from 'fs'
  export default {
    components: {
      AddStaff,
      ListFilter,
      ListFields,
      HeadPortrait,
    },
    mixins: [listMixin],
    data() {
      return {
        tableHeight: '500',
        url: this.$imgUrl + '/Employee/ImportEmployee',
        filename: 'employees',
        autoWidth: true,
        bookType: 'xlsx',
        timeId: "",
        // 部门
        dptList: [],
        // 职位
        jobList: [],
        // 工种
        workList: [],
        // 在职状态
        statusList: [],
        deleteList: {
          id: "",
        },
        // 查询字段
        topFilter: {},
        // 关键字查询
        keyList: [
          "employeeCode",
          "name",
          "birthday",
          "idCard",
          "phone",
          "email",
          "adress",
          "comment",
          "department.deptName",
          "job.jobTitle",
          "work.workName",
          "rfid",
          "status",
          "accessCardID",
        ],
        // 列表数据
        tableData: [],
        // 列表表头
        tableCol: [
          { type: "selection", height: "250" },
          { prop: "employeeCode", label: "员工编码", align: "center", minWidth: '120px' },
          { prop: "name", label: "员工姓名", align: "center", minWidth: '80px' },
          {
            prop: "sex",
            label: "性别",
            align: "center",
            minWidth: '54px',
            formatter(row, col, cell) {
              let sex,
                sexList = [
                  { label: "男", value: 1 },
                  { label: "女", value: 0 },
                ]
              sexList.forEach((item) => {
                if (item.value == cell) {
                  sex = item.label
                }
              })
              return sex
            },
          },
          {
            prop: 'birthday', label: '生日', align: 'center', minWidth: '96px',
            formatter(row, col, cell) {
              let date = new Date(cell)
              let year = date.getFullYear()
              let month = date.getMonth() + 1
              month = month >= 10 ? month : '0' + month
              let d1 = date.getDate()
              d1 = d1 >= 10 ? d1 : '0' + d1
              let time_str = year + '-' + month + '-' + d1
              return cell ? time_str : '--'
            }
          },
          { prop: "idCard", label: "身份证号", align: "center", minWidth: '166px' },
          { prop: "phone", label: "手机号", align: "center", minWidth: '110px' },
          { prop: "email", label: "邮箱", align: "center", minWidth: '180px' },
          { prop: "adress", label: "地址", align: "center", minWidth: '200px' },
          {
            prop: "photo",
            label: "照片",
            custom: "col2",
            minWidth: "80px",
            align: "center",
          },
          {
            prop: "departmentId",
            label: "部门",
            minWidth: '80px',
            align: "center",
            formatter(row, col, cell) {
              return row.department ? row.department.deptName : "--"
            },
          },
          {
            prop: "jobId",
            label: "职位",
            minWidth: '80px',
            formatter(row, col, cell) {
              return row.job ? row.job.jobTitle : "--"
            },
            align: "center",
          },
          {
            prop: "workId",
            label: "工种",
            minWidth: '80px',
            formatter(row, col, cell) {
              return row.work ? row.work.workName : "--"
            },
            align: "center",
          },
          { prop: "rfid", label: "RFID卡", minWidth: '80px', align: "center" },
          { prop: "accessCardID", label: "门禁ID", minWidth: '80px', align: "center" },
          {
            prop: "status",
            label: "工作状态",
            minWidth: '80px',
            formatter(row, col, cell) {
              return row.status == 1 ? "在职" : "离职"
            },
            align: "center",
          },
          {
            prop: "faceDetect",
            label: "人脸识别",
            minWidth: '80px',
            formatter(row, col, cell) {
              return row.faceDetect === 1 ? "启用" : "禁用"
            },
            align: "center",
          },
          {
            prop: "isEnable",
            label: "门禁启用/禁用",
            minWidth: '118px',
            formatter(row, col, cell) {
              return row.isEnable ? "启用" : "禁用"
            },
            align: "center",
          },
          { prop: "comment", label: "备注", align: "center", minWidth: '180px' },
          { label: "操作", custom: "col1", align: "center", minWidth: '108px', fixed: 'right' },
        ],
        tabList: [{ type: "selection" }],
        tableColValue: [],
        // 启用禁用
        isEnableSwitch: false,
        downloadLoading: false,
        selectionList: []
      }
    },
    mounted() {
      // 获取下拉框数据并赋值给查询组件
      this.threeList(() => {
        this.topFilter = {
          departmentId: {
            label: "部门",
            placeholder: "请选择员工部门",
            type: "select",
            arr: this.dptList,
          },
          jobId: {
            label: "职位",
            placeholder: "请选择员工职位",
            type: "select",
            arr: this.jobList,
          },
          workId: {
            label: "工种",
            placeholder: "请选择员工工种",
            type: "select",
            arr: this.workList,
          },
          status: {
            label: "工作状态",
            placeholder: "请选择工作状态",
            type: "select",
            arr: [
              { label: "在职", value: 1 },
              { label: "离职", value: 2 },
            ],
          },
          keyword: {
            label: "关键字",
            placeholder: "请输入员工编码或姓名、RFID、门禁ID",
          },
        }
      })
      let listTable = localStorage.getItem("listTabel")
      if (!listTable) {
        this.tabList = this.tableCol
        return
      }
      this.tabList = [{ type: "selection" }]
      this.tableColValue = JSON.parse(listTable)
      this.tableColValue.forEach(item => {
        this.tableCol.forEach(edit => {
          if (item.label === edit.label) {
            this.tabList.push(edit)
          }
        })
      })
    },
    methods: {
      async changItemHandler(obj) {
        if (!obj.val) {
          return
        }
        if (obj.key === "departmentId") {
          this.arr = this.jobList.filter(item => {
            return item.department.id == obj.val
          })
          this.topFilter.jobId.arr = this.arr
        }
      },
      // 上传成功
      handleAvatarSuccess(res, file) {
        if (!res) {
          this.$refs.imgRef.clearFiles()
          return
        }
        if (res.code === 200) {
          this.$message.success('上传成功！')
          this.$refs.imgRef.clearFiles()
        }

      },
      // 上传前
      beforeAvatarUpload(file) {
        const isJPG = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        // const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error("上传的文件只能是 xlsx 类型!")
        }
        // if (!isLt2M) {
        //   this.$message.error("上传头像图片大小不能超过 2MB!")
        // }
        return isJPG
        // && isLt2M
      },
      async uploadFile(value) {
        try {
          let pat = value.file.path
          // let pat = 'C:/Users/Administrator/Desktop/employees.xlsx'
          await importEmployee(pat)
        } catch (err) {
          console.log(err)
        }

      },
      // 批量导出
      handleOut() {
        if (this.selectionList.length === 0) {
          this.$message.warning('请先选中要导出的数据！')
        } else {
          this.handleDownload({}, this.selectionList)
        }
      },
      // 下载模板
      async handleDownload(event, value) {
        this.downloadLoading = true
        // 保存所有数据
        let obj = []
        // 保存标题
        let objTitle = []
        // 批量下载时保存标题
        let titleList = []
        // 得到下载的数据
        let list = []
        let dataList = []
        if (!value) {
          // let res = await employees()
          // location.href = this.$imgUrl + '/files/employees.xlsx'
          // 读取模板文件
          // const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`${__dirname}/../../../assets/employees.xlsx`))
          // let pat = process.cwd()
          // const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(pat + '/employees.xlsx'))
          // // // 得到模板文件数据
          // obj = workSheetsFromBuffer[0].data
          // // 得到模板文件标题
          // objTitle = JSON.parse(JSON.stringify(obj[0]))
          // // 删除标题
          // delete obj[0]
          // // 循环得到下载的数据
          // obj.forEach((item) => {
          //   let ary = {}
          //   objTitle.forEach((edit, index) => {
          //     ary[edit] = item[index]
          //   })
          //   list.push(ary)
          // })
        } else {
          // 得到下载的数据
          obj = value
          // 得到标题
          this.tableColValue.forEach(item => {
            titleList.push({
              label: item.label,
              value: item.prop
            })
            objTitle.push(item.label)
          })
          // 得到数据结构对应的数据
          obj.forEach(edit => {
            let ary = {}
            titleList.forEach(titl => {
              if (titl.value === 'departmentId') {
                ary.departmentId = edit.department.deptName
              } else if (titl.value === 'jobId') {
                ary.jobId = edit.job.jobTitle
              } else if (titl.value === 'workId') {
                ary.workId = edit.work ? edit.work.workName : '无'
              } else {
                ary[titl.value] = edit[titl.value]
              }
              // if ()
            })
            dataList.push(ary)
          })

          dataList.forEach(a => {
            a.sex = a.sex == 1 ? '男' : '女'
            a.status = a.status == 1 ? '在职' : '离职'
            a.faceDetect = a.faceDetect === 1 ? "启用" : "禁用"
            a.isEnable = a.isEnable ? "启用" : "禁用"
          })
          // 再次转换
          dataList.forEach(da => {
            let ary = {}
            let keeList = Object.keys(da)
            keeList.forEach(kee => {
              titleList.forEach(lis => {
                if (kee === lis.value) {
                  ary[lis.label] = da[kee]
                }
              })
            })
            list.push(ary)
          })
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = objTitle
            const filterVal = objTitle
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename,
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
            this.downloadLoading = false
          })
        }
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      // 启用禁用门禁
      async setEmployeeHandle(value) {
        try {
          let res = await setEmployee("POST", {
            employeeId: value.id,
            isEnable: !value.isEnable,
          })
          if (res.code !== 200) {
            return
          }
          this.getList()
        } catch (err) {
          console.log(err)
        }
      },
      // 设置表头
      setTableColHandler(value) {
        this.tabList = []
        this.tabList = [{ type: "selection" }, ...value]

        this.tableColValue = value
        localStorage.setItem("listTabel", JSON.stringify(this.tableColValue))
      },
      // 选择表单字段
      addHandle() {
        this.$refs.ListFields.open()
        this.$refs.ListFields.selectionChange(this.tableColValue)
      },
      // 查询部门，职位，工种
      async threeList(fn) {
        try {
          let obj = { pageIndex: 1, pageSize: 1e8 }
          let resList = await Promise.all([
            department("post", obj, false),
            job("post", obj, false),
            work("post", obj, false),
          ])
          // 部门
          if (resList[0].code === 200) {
            this.dptList = resList[0].data.items.map((item) => {
              if (item.lenght === 0) {
                return
              }
              return {
                label: item.deptName,
                value: item.id,
              }
            })
          }
          // 职位
          if (resList[1].code === 200) {
            this.jobList = resList[1].data.items.map((item) => {
              if (item.lenght === 0) {
                return
              }
              return {
                label: item.jobTitle,
                value: item.id,
                department: item.department
              }
            })
          }
          // 工种
          if (resList[2].code === 200) {
            this.workList = resList[2].data.items.map((item) => {
              if (item.lenght === 0) {
                return
              }
              return {
                label: item.workName,
                value: item.id,
              }
            })
          }
        } catch (err) {
          console.log(err)
        }
        fn()
      },
      // 打开上传头像组件
      addHeadPortrait() {
        this.$refs["HeadPortrait"].open()
      },
      // 批量删除
      batchDeletion() {
        if (!this.deleteList.id) {
          this.$message.warning('请选择要删除的数据！')
          return
        }
        this.$_delConfirm("选中员工", () => {
          this.delRowReq(this.deleteList)
        })
      },
      // 选中事件
      handleSelectionChange(event) {
        this.selectionList = event
        if (event.length > 0) {
          let ary = []
          event.forEach((item) => {
            ary.push(item.id)
          })
          if (ary.length > 1) {
            this.deleteList.id = ary.join(",")
          } else {
            this.deleteList.id = ary[0]
          }
        } else {
          this.deleteList.id = ""
        }
      },
      // 请求列表数据
      async getList(query) {
        this.tableLoading = true
        try {
          let obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'createdTime', orderByAscent: false }
          const {
            data: { items: resData, count, pageIndex },
          } = await employee("post", obj, false)
          this.tableData = []
          this.tableData = resData.map((item) => {
            item.loadingEdit = false
            item.loadingDel = false
            item.isEnable
              ? (this.isEnableSwitch = true)
              : (this.isEnableSwitch = false)
            return item
          })
          this.$nextTick(() => {
            this.$refs["RefListTable"].update({ page: pageIndex, count })
            this.tableLoading = false
          })
        } catch (err) {
          this.tableLoading = false
          console.error("getList err: ", err)
        }
      },
      async afterEditSuccess() {
        await this.$router.push({ query: {} })
        this.getList()
      },
      handleAdd() {
        this.$refs["RefAccountsEdit"].open()
        this.$refs["RefAccountsEdit"].getList()
        this.$refs["RefAccountsEdit"].getMaxId()
      },
      handleRowEdit(row) {
        this.$refs["RefAccountsEdit"].open(row)
        this.$refs["RefAccountsEdit"].getList()
      },
      handleRowSee(row) {
        this.$refs["RefAccountsEdit"].open(row, false, true)
        this.$refs["RefAccountsEdit"].getList()
      },
      async delRowReq(row) {
        try {
          const obj = { id: row.id, value: null }
          await employee("delete", obj, true)
          row.loadingDel = false
          await this.$router.push({ query: {} })
          this.getList()
          this.$message({
            type: "success",
            message: "删除成功",
          })
        } catch (err) {
          row.loadingDel = false
          this.$message({
            type: 'error',
            message: '删除失败'
          })
          console.error("handleRowDel err: ", err)
        }
      },
      handleRowDel(row) {
        row.loadingDel = true
        this.$_delConfirm(
          "该员工",
          () => {
            this.delRowReq(row)
          },
          () => {
            row.loadingDel = false
          }
        )
      },
    },
  }
</script>

<style lang="scss" scoped>
  a {
    text-decoration: none;
  }
  /*正常的未被访问过的链接*/
  a:link {
    text-decoration: none;
  }
  /*已经访问过的链接*/
  a:visited {
    text-decoration: none;
  }
  /*鼠标划过(停留)的链接*/
  a:hover {
    text-decoration: none;
  }
  /* 正在点击的链接*/
  a:active {
    text-decoration: none;
  }
  .download {
    color: #fff;
    display: inline-block;
    padding: 10px 20px;
    background-color: #1890ff;
    margin: 0 10px;
    border-radius: 3px;
  }
</style>
